package com.example.tourism.config;

import com.example.tourism.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private static final List<String> WHITE_LIST_URLS = Arrays.asList(
            "/user/login",
            "/user/register",
            "/user/checkVerifyCode",
            "/user/sendEmail",
            "/user/refreshToken",
            "/home/recommends",
            "/test/test",
            "/alipay/pay",
            "/alipay/notify",
            "/rabbitMQ/send"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestURI = request.getRequestURI();
        String accessToken = request.getHeader("Authorization");

        if (WHITE_LIST_URLS.contains(requestURI)) {
            return true;
        }

        if (accessToken != null && accessToken.startsWith("Bearer ")) {
            accessToken = accessToken.substring(7);
            try {
                if (TokenUtil.verifyToken(accessToken)) {
                    String Id = TokenUtil.getId(accessToken);
                    request.setAttribute("Id", Id);
                    return true;
                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("拦截器出现错误");
                    return false;
                }
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("短token过期");
                return false;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("不存在Token");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // This method is called after the handler execution.
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // This method is called after the complete request has finished.
    }
}
